<template>
  <el-dialog
    v-model="visible"
    title="账户管理"
    :width="dialogWidth"
    :before-close="handleClose"
    @close="handleClose"
    :class="{ 'mobile-dialog': isMobile }"
  >
    <div class="account-management">
      <!-- 工具栏 -->
      <div class="toolbar">
        <el-button type="primary" @click="showAddAccountModal = true" class="add-button">
          <el-icon><Plus /></el-icon>
          添加账户
        </el-button>
      </div>

      <!-- 账户列表 -->
      <el-row :gutter="24" class="accounts-grid">
        <el-col :span="8" :sm="12" :md="8" :lg="6" v-for="account in accounts" :key="account.id">
          <el-card class="account-card" shadow="hover">
            <div class="card-content">
              <div class="account-icon" :style="{ backgroundColor: account.color || '#007aff' }">
                <span v-if="account.icon">{{ account.icon }}</span>
                <el-icon v-else><Wallet /></el-icon>
              </div>
              <div class="account-info">
                <h3 class="account-name">{{ account.name }}</h3>
                <p class="account-type">{{ getAccountTypeLabel(account.account_type) }}</p>
                <div class="account-balance" :class="{ 'positive': parseFloat(account.balance) >= 0, 'negative': parseFloat(account.balance) < 0 }">
                  ¥{{ formatAmount(parseFloat(account.balance)) }}
                </div>
              </div>
              <div class="account-actions">
                <el-button size="small" @click="editAccount(account)" :icon="Edit" circle />
                <el-button size="small" type="danger" @click="deleteAccount(account)" :icon="Delete" circle />
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 空状态 -->
      <el-empty v-if="accounts.length === 0" description="暂无账户">
        <el-button type="primary" @click="showAddAccountModal = true">
          添加第一个账户
        </el-button>
      </el-empty>
    </div>

    <!-- 添加账户弹窗 -->
    <AddAccountModal
      v-model:visible="showAddAccountModal"
      :edit-data="editAccountData"
      @close="handleAccountModalClose"
      @success="handleAccountSuccess"
    />
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, watch } from 'vue';
import { useAccountingStore } from '@/stores/accounting';
import { Plus, Edit, Delete, Wallet } from '@element-plus/icons-vue';
import AddAccountModal from './AddAccountModal.vue';
import type { AccountResponse, AccountType } from '@/types/accounting';

interface Props {
  visible: boolean;
}

interface Emits {
  (e: "update:visible", visible: boolean): void;
  (e: "close"): void;
  (e: "success"): void;
}

const props = defineProps<Props>();
const emit = defineEmits<Emits>();

const accountingStore = useAccountingStore();

// 响应式数据
const accounts = ref<AccountResponse[]>([]);
const showAddAccountModal = ref(false);
const editAccountData = ref<AccountResponse | null>(null);

// 响应式布局
const isMobile = ref(false);
const dialogWidth = computed(() => isMobile.value ? '95%' : '80%');

// 检查屏幕尺寸
const checkScreenSize = () => {
  isMobile.value = window.innerWidth < 768;
};

onMounted(() => {
  checkScreenSize();
  window.addEventListener('resize', checkScreenSize);
});

onUnmounted(() => {
  window.removeEventListener('resize', checkScreenSize);
});

// 计算属性
const visible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
});

// 获取账户列表
const fetchAccounts = async () => {
  try {
    await accountingStore.fetchAccounts();
    accounts.value = accountingStore.accounts;
  } catch (error) {
    console.error('获取账户列表失败:', error);
  }
};

// 获取账户类型标签
const getAccountTypeLabel = (type: AccountType): string => {
  const typeLabels: Record<AccountType, string> = {
    cash: '现金',
    bank: '银行',
    credit_card: '信用卡',
    alipay: '支付宝',
    wechat: '微信',
    other: '其他',
  };
  return typeLabels[type] || type;
};

// 格式化金额
const formatAmount = (amount: number): string => {
  return amount.toFixed(2);
};

// 编辑账户
const editAccount = (account: AccountResponse) => {
  editAccountData.value = account;
  showAddAccountModal.value = true;
};

// 删除账户
const deleteAccount = async (account: AccountResponse) => {
  if (!confirm('确定要删除这个账户吗？')) {
    return;
  }

  try {
    await accountingStore.deleteAccount(account.id);
    await fetchAccounts();
  } catch (error) {
    console.error('删除账户失败:', error);
    alert('删除账户失败，请重试');
  }
};

// 处理账户成功
const handleAccountSuccess = async () => {
  editAccountData.value = null;
  await fetchAccounts();
  emit('success');
};

// 处理账户弹窗关闭
const handleAccountModalClose = () => {
  editAccountData.value = null;
  showAddAccountModal.value = false;
};

// 处理弹窗关闭
const handleClose = () => {
  emit('close');
  emit('update:visible', false);
};

// 监听visible变化
watch(() => props.visible, async (newVisible) => {
  if (newVisible) {
    await fetchAccounts();
  }
});
</script>

<style lang="scss" scoped>
.account-management {
  .toolbar {
    margin-bottom: 24px;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .add-button {
      border-radius: var(--el-border-radius-small);
      font-weight: 500;
      padding: 10px 20px;
      transition: all 0.3s ease;
      
      &:hover {
        transform: translateY(-1px);
        box-shadow: var(--el-box-shadow-light);
      }
    }
  }

  .accounts-grid {
    .el-col {
      margin-bottom: 20px;
    }
  }

  .account-card {
    transition: all 0.3s ease;
    height: 100%;
    border-radius: var(--el-border-radius-base);
    border: 1px solid var(--el-border-color);
    
    &:hover {
      transform: translateY(-2px);
      box-shadow: var(--el-box-shadow-light);
      border-color: var(--el-color-primary);
    }

    .card-content {
      display: flex;
      align-items: center;
      padding: 16px;
      gap: 16px;
    }
  }

  .account-icon {
    width: 56px;
    height: 56px;
    border-radius: var(--el-border-radius-base);
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    flex-shrink: 0;
    font-size: 20px;
    font-weight: 600;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
    transition: all 0.3s ease;
    
    &:hover {
      transform: scale(1.1);
    }
  }

  .account-info {
    flex: 1;
    min-width: 0;
  }

  .account-name {
    font-size: 16px;
    font-weight: 600;
    color: var(--el-text-color-primary);
    margin: 0 0 8px 0;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .account-type {
    font-size: 12px;
    color: var(--el-text-color-secondary);
    margin: 0 0 8px 0;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .account-balance {
    font-size: 16px;
    font-weight: 600;
    margin: 0;
    
    &.positive {
      color: var(--el-color-success);
    }
    
    &.negative {
      color: var(--el-color-danger);
    }
  }

  .account-actions {
    display: flex;
    align-items: center;
    gap: 8px;
    flex-shrink: 0;
    
    .el-button {
      transition: all 0.3s ease;
      
      &:hover {
        transform: scale(1.1);
      }
    }
  }
}

@media (max-width: 768px) {
  .accounts-grid {
    .el-col {
      margin-bottom: 12px;
    }
  }
  
  .account-management {
    .toolbar {
      margin-bottom: 16px;
      
      .add-button {
        padding: 8px 16px;
        font-size: 13px;
      }
    }
  }
  
  :deep(.el-dialog) {
    margin: 0 !important;
    margin-top: 20px !important;
  }
}

@media (max-width: 480px) {
  .accounts-grid {
    .el-col {
      margin-bottom: 8px;
    }
  }
  
  .account-card {
    .card-content {
      padding: 12px;
      gap: 12px;
    }
  }
  
  .account-icon {
    width: 48px;
    height: 48px;
    font-size: 18px;
  }
  
  .account-name {
    font-size: 14px;
  }
  
  .account-type {
    font-size: 11px;
  }
  
  .account-balance {
    font-size: 14px;
  }
}

// 移动端弹窗样式
:deep(.mobile-dialog) {
  .el-dialog {
    margin: 0 !important;
    margin-top: 10px !important;
    border-radius: var(--el-border-radius-small);
  }
  
  .el-dialog__body {
    padding: 16px;
  }
}
</style>